package cmd

import (
	"cobra-viper-demo/config"
	"errors"
	"fmt"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func NewMysqlCmd() *cobra.Command {
	mysqlCmd := &cobra.Command{
		Use:   "mysql [OPTIONS] [COMMANDS]",
		Short: "mysql the those message",
		Long:  `mysql the special message`,
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("run print...")
			fmt.Printf("mysql url: %#v\n", config.ServerConfig.Mysql.Url)
			// 使用rootCmd中的参数 需要在rootCmd开启 TraverseChildren: true,
		},
		Args: func(cmd *cobra.Command, args []string) error {
			if len(args) < 1 {
				return errors.New("requires at least one arg")
			}
			if args[0] != "a" {
				return errors.New("first argument must be 'a'")
			}
			return nil
		},
	}

	// go run main.go mysql a --mysql-url="this is not config.yaml config"
	mysqlCmd.Flags().StringVar(&config.ServerConfig.Mysql.Url, "mysql-url", config.ServerConfig.Mysql.Url, "mysql url string")
	viper.BindPFlag("mysql.url", mysqlCmd.Flags().Lookup("mysql-url"))

	return mysqlCmd
}
